package org.android.bbox.data;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DbHelper
{
	public static final String DATABASE_NAME = "bbox_data.sqlite";

	public static final String TABLE_PROFILS = "profils";

	private final Context mContext;

	private final SQLiteDatabase db;

	public DbHelper(Context mContext) throws NoDatabaseException
	{
		this.mContext = mContext;

		Db dbHelper = new Db(this.mContext);

		this.db = dbHelper.getWritableDatabase();
		if (this.db == null)
		{
			throw new NoDatabaseException(DATABASE_NAME);
		}
	}

	public SQLiteDatabase getDatabase()
	{
		return this.db;
	}

	protected void finalize() throws Throwable
	{
		this.db.close();
		super.finalize();
	}

	private class Db extends SQLiteOpenHelper
	{
		private static final int DATABASE_VERSION = 2;

		public Db(Context context)
		{
			super(context, DbHelper.DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db)
		{
			//CREATE ALL TABLES
			db.execSQL("CREATE TABLE " + DbHelper.TABLE_PROFILS + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
					+ "name VARCHAR(60) NOT NULL, ip VARCHAR(15) NOT NULL, login VARCHAR(60) NOT NULL, "
					+ "password VARCHAR(60) DEFAULT NULL, password_user VARCHAR(60) DEFAULT NULL, "
					+ "save_password BOOLEAN DEFAULT FALSE, image VARCHAR(120) DEFAULT NULL, color CHAR(6) DEFAULT NULL)");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
		{
			Log.w("ProfileProvider", "Upgrading database from version " + oldVersion + " to " + newVersion
					+ ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS " + DbHelper.TABLE_PROFILS);
			onCreate(db);
		}
	}
}
